package cn.lyq.card.ui.address

import android.content.Context
import android.content.Intent
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import cn.lyq.card.R
import cn.lyq.card.base.BaseActivity
import cn.lyq.card.data.src.Status
import cn.lyq.card.global.BusTag
import cn.lyq.card.manager.UserManager
import cn.lyq.card.utils.hasIndex
import cn.lyq.card.utils.setClick
import com.blankj.utilcode.util.BusUtils
import com.blankj.utilcode.util.ToastUtils
import kotlinx.android.synthetic.main.act_address_manager.*

class AddressManagerActivity : BaseActivity() {

    private val mModel by lazy {
        getVM(AddressVM::class.java)
    }
    private val mAdapter by lazy {
        AddressAdapter()
    }
    private val mAddressId by lazy {
        intent.getIntExtra(KEY_ID, -1)
    }

    companion object {
        private const val KEY_ID = "ID"

        /**
         * 未选中传0
         */
        @JvmStatic
        fun start(context: Context, id: Int) {
            val starter = Intent(context, AddressManagerActivity::class.java)
                .putExtra(KEY_ID, id)
            context.startActivity(starter)
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.act_address_manager
    }

    override fun initView() {
        super.initView()
        setMyTitle(R.string.str_address_manager)

        tvAddAddress.setClick {
            startActivity(AddressAddActivity::class.java)
        }
        rv.layoutManager = LinearLayoutManager(this)
        rv.adapter = mAdapter
        mAdapter.setEmptyView(R.layout.layout_empty_address)
        mAdapter.setID(mAddressId)
    }

    override fun initListener() {
        super.initListener()
        mAdapter.addChildClickViewIds(R.id.tvDefault, R.id.tvDel, R.id.tvEdit, R.id.tvUse)
        mAdapter.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.tvDefault -> updateDefault(position)
                R.id.tvDel -> deleteAddress(position)
                R.id.tvEdit -> AddressAddActivity.start(this, mAdapter.data[position])
                R.id.tvUse -> {
                    BusUtils.post(BusTag.ADDRESS_SELECT, mAdapter.data[position])
                    finish()
                }
            }
        }

        refreshLayout.setOnRefreshListener {
            getData()
        }
    }

    override fun initObserver() {
        super.initObserver()
        refreshLayout.isRefreshing = true
        getData()
    }

    private fun getData() {
        mModel.getList().observe(this, Observer {
            when (it?.status) {
                Status.SUCCESS -> {
                    refreshLayout.isRefreshing = false
                    mAdapter.setList(it.requireData())
                    UserManager.setDefaultAddress(mAdapter.data)
                    if (mAddressId != -1 && mAddressId != 0) {
                        updateSelectAddress()
                    }
                }
                Status.ERROR -> {
                    refreshLayout.isRefreshing = false
                    ToastUtils.showShort(it.message.getMsg())
                }
                else -> {
                }
            }
        })
    }

    private fun updateSelectAddress() {
        mAdapter.data.forEach {
            if (mAddressId == it.id) {
                BusUtils.post(BusTag.ADDRESS_SELECT, it)
            }
        }
    }

    private fun deleteAddress(position: Int) {
        mModel.delIndex = position
        AddressConfirmDelFg().show(supportFragmentManager)
    }

    private fun updateDefault(position: Int) {
        val address = mAdapter.data[position]
        if (address.isDefault()) {
            return
        } else {
            address.default = 1
        }
        mModel.editAndAdd(address).observe(this, Observer {
            when (it?.status) {
                Status.LOADING -> refreshLayout.isRefreshing = true
                Status.SUCCESS -> {
                    mAdapter.defaultIndex
                        .takeIf { index ->
                            index != -1 && mAdapter.data.hasIndex(index)
                        }?.run {
                            mAdapter.data[this]
                        }?.run {
                            default = 0
                            mAdapter.setData(mAdapter.defaultIndex, this)
                        }
                    mAdapter.setData(position, address)
                    refreshLayout.isRefreshing = false
                }
                Status.ERROR -> {
                    refreshLayout.isRefreshing = true
                    ToastUtils.showShort(it.message.getMsg())
                }
            }
        })
    }

    @BusUtils.Bus(tag = BusTag.ADDRESS_REFRESH, threadMode = BusUtils.ThreadMode.MAIN)
    fun refresh() {
        refreshLayout.isRefreshing = true
        getData()
    }

    @BusUtils.Bus(tag = BusTag.ADDRESS_DEL, threadMode = BusUtils.ThreadMode.MAIN)
    fun addressDel() {
        if (mModel.delIndex == -1) {
            return
        }
        val delIndex = mModel.delIndex
        val delId = mAdapter.data[delIndex].id
        mModel.delIndex = -1
        mModel.del(delId).observe(this, Observer {
            when (it?.status) {
                Status.LOADING -> showLoading()
                Status.SUCCESS -> {
                    mAdapter.removeAt(delIndex)
                    UserManager.setDefaultAddress(mAdapter.data)
                    if ( delId == mAddressId) {
                        BusUtils.post(BusTag.ADDRESS_SELECT, null)
                    }
                    dismissLoading()
                }
                Status.ERROR -> {
                    ToastUtils.showShort(it.message.getMsg())
                    dismissLoading()
                }
            }
        })
    }
}